import config from '../config.js'
export let header = {
  'Content-Type': 'application/json',
}
export const http = {
  paramScreen: function (data){
    Object.keys(data).forEach(value=>{
      if(data[value] === ""||typeof data[value] == 'undefined'){
        delete data[value]
      }
    })
    return data
  },
  //请求方法
  requset: function (method, url, parameter = {}) {
    let data = this.paramScreen(parameter)
    return new Promise((resolve, reject) => {
      wx.request({
        header: {
          ...header
        },
        method: method,
        url: url,
        data: data,
        success: (e) => {
          this.requsetSuccess(e, resolve, reject)
        },
        fail: function (e) {
          wx.hideLoading()
          reject(res);
        }
      })
    })
  },
  //验证方法
  requsetSuccess: function (res, resolve, reject) {
    switch (res.data.status) {
      case 200:
        resolve(res.data.data)
        break
      case 400:
        wx.hideLoading()
        wx.showToast({
          title:res.data.message,
          icon:'none'
        })
        reject(res.data.message)
      default:
        wx.hideLoading()
        wx.showToast({
          title:res.data.message,
          icon:'none'
        })
        reject(res.data.message)
        break
    }
  },
  //设置Token方法
  setHeader:function(key,value){
    header.Authorization = `Bearer ${value}`
    wx.setStorageSync('token', value)
    return {
      value:header[key],
      key:key
    }
  },
  //清除Token方法
  removeTokenSync:function(){
    if(header.Authorization){
      delete header.Authorization
    }
    wx.removeStorageSync('token')
  },
  //get请求
  GET: function (url, data) {
    return this.requset('GET', this.urlSplicing(url), data)
  },
  //post请求
  POST: function (url, data) {
    return this.requset('POST', this.urlSplicing(url), data)
  },
  //url处理
  urlSplicing: function (url) {
    return config.data.url + url
  }
}